/**
 * 集成ext formpanel控件，实现动态创建表单，表单字段排版
 * @author：xuqiang
 * @date：2016-11-03
 */
Ext.namespace("Ext.com.bkfm");
Ext.define('Ext.com.bkfm.form', {
	extend:"Ext.form.Panel",
	layoutMode : 'table',
	columnCount : 4, // 显示列
	frameBorder: true,
	autoScroll: true,
	border: true,
	labelAlign : 'right',
	textOnly: false,	//是否文本只读
	textOnlyField: null,//只读字段
	hiddenField: null,//隐藏字段,可以通过表单对象获取到
	unViewField: null,//不显示字段，不可以通过表单对象获取
	requiredField:[],//设置必填字段
	//fieldSetMode: true,	//是否需要分组显示
	labelWidth: 80,		//默认标签显示宽度
	defaultWidth: 250,//字段默认宽度
	labelSeparator: '：',	//标签和输入框之间的分隔符
	formState: Constants.RECORD_NEW, // 表单状态为new，changed
	guid: '',//表单记录的id序号
	objPath : '', // 建模对象路径
	saveObjPath: null,	//数据保存的建模对象,空则去objPath的建模对象保存
	fieldItems: null,//表单字段列表信息
	formItems: null,		//所有表单列表数组
	showGroup: false,//是否分组显示
	groupSet:null,
	initComponent: function(){
		if(Ext.isEmpty(this.objPath)){
			AjaxUtils.showError('创建表格异常，无效的存储参数');
			this.callParent(arguments);
			return;
		}
		if(this.showGroup){
			Ext.apply(this, {
				layout: {
					type: this.layoutMode,
					columns: 1,
					forceFit : true
				},
				bodyStyle:'padding:10px 10px 10px 10px;'
			});
		}else{
			Ext.apply(this, {
				layout: {
					type: this.layoutMode,
					columns: this.columnCount
				},
				bodyStyle:'padding:10px 10px 10px 10px'
			});
		}

		this.formItems = new Array();
		this.fieldItems = new Array();
		this.getServiceModelMeta();
		this.callParent(arguments);


		//添加自定义事件
		this.addEvents("beforeSave");
	},
	//获取服务器建模属性
	getServiceModelMeta: function(){
		var form = this;
		AjaxUtils.CallJsonService({
			url: CONTEXT.contextPath+"/bkfm/metadata/v1/querytablemetacolumn",
			params: {
				"obj_path": form.objPath
			},
			call: function(data){
				form.initFormPanel(data);
			}
		});
	},
	//初始化表单
	initFormPanel: function(data){
		if(this.showGroup){
			//分组
			this.initFormGroup(data);
		}else{
			//不分组
			this.initFormElement(data);
		}
		this.items = this.formItems;
	},
	//生成表单页面元素
	initFormElement: function(meta){
		var fieldIndex = 0;
		for(i in meta.list){
			/*var metaField = meta.entity[i];
			var field = this.createFormField(metaField);
			检查是否需要合并行单元格
			fieldIndex = this.colspanFieldCell(metaField,field,fieldIndex,null);
			this.formItems.push(field);*/


			var metaField = meta.list[i];
			var field = this.createFormField(metaField);
			if(field == null){
				continue;
			}
			if(Ext.isEmpty(this.itemSize)){
				this.itemSize = 1;
			}else{
				this.itemSize = this.itemSize +1;
			}
			//检查是否需要合并行单元格
			this.colspanFieldCell(metaField,field,this.itemSize-1,this);
			//将元素添加到面板
			this.formItems.push(field);

		}
	},
	//创建表单元素
	createFormField: function(metaField){
		var form = this;
		var field = null;
		var allowBlank = true;
		//输入内容长度
		var fieldlength = parseInt(metaField.model_field_len);
		/**
		 * 字段可为空，非主键
		 */
		//alert(metaField.is_empty+":"+metaField.is_primary_key+":"+(metaField.is_empty == Constants.YES || metaField.is_primary_key == Constants.NO))
		if(metaField.is_primary_key == Constants.YES){
			//必填
			allowBlank = false;
		}else if(metaField.is_empty == Constants.NO){
			//必填
			allowBlank = false;
		}else{
			//必填
			allowBlank = true;
		}
		//文本框是否可编辑，默认可编辑
		var field_editable = false;
		var is_disabled = metaField.is_disabled;
		if(is_disabled == Constants.NO){
			field_editable = true;
		}
		
		//是否可以预览，Y在表单页面显示，N不在表单页面显示
		var is_view = metaField.is_viewer;
		if(is_view == Constants.NO){
			return null;
		}
		if(Ext.isArray(this.unViewField)){
			if(Ext.Array.contains(this.unViewField,metaField.en_us)){
				//当前字段在不可预览字段列表中，返回空
				return null;
			}
		}

		if(Ext.isEmpty(metaField.user_config)){
			field = Ext.create('Ext.form.field.Text',{
				msgTarget:'side',
				fieldLabel: metaField.zh_cn,
				name: metaField.en_us,
				id: metaField.en_us,
				labelAlign: form.labelAlign,
				labelWidth: form.labelWidth,
				labelSeparator: form.labelSeparator,
				minWidth: form.defaultWidth,
				width: form.defaultWidth,
				allowBlank: allowBlank,
				maxLength: fieldlength,
				style: "margin-top:10px;",
				readOnly: field_editable,
				style: "margin-top:10px;",
				enableKeyEvents: true,
				//anchor:'90%'
			});
		}else{
			var config = Ext.JSON.decode(metaField.user_config);
			var ftype = config.ftype;
			var required = config.required || false;
			if(required){
				//必填
				allowBlank = false;
			}
			if(allowBlank){
				//如果当前字段不是非必填，判断requiredField列表中是否个性化设置了必填字段
				if(Ext.Array.contains(this.requiredField,metaField.en_us)){
					//存在必填字段
					alowBlank = false;
				}
			}
			switch(ftype){
				case Constants.FIELDSELECT:{
						//判断该字段是否有动态关联字段
						var linkage = config.linkage || false;
						//动态关联字段
						var linkagefield = config.linkagefield || "";
						//动态关联字段的查询字段
						var linkagefilterfield = config.linkagefilterfield || "";

						field = Ext.create("Ext.com.bkfm.combobox",{
							msgTarget:'side',
							fieldLabel: metaField.zh_cn,
							name: metaField.en_us,
							id: metaField.en_us,
							labelAlign: form.labelAlign,
							labelWidth: form.labelWidth,
							labelSeparator: form.labelSeparator,
							minWidth: form.defaultWidth,
							width: form.defaultWidth,
							allowBlank: allowBlank,
							editable: false,
							objPath: metaField.obj_path,
							loadingText:'加载中……',
							style: "margin-top:10px;",
							listeners:{
								change: function(obj,value,oldvalue,opts){
									//判断是否存在动态二级菜单
									if(linkage && !Ext.isEmpty(linkagefield)){
										var linkage_field = form.findById(linkagefield);
										var fieldtype = linkage_field.getXType();
										if(fieldtype=="select"){
											//关联关系查询sql中需要增加FATHER_VALUE字段，所属父节点
											linkage_field.setFilter("  FATHER_VALUE='"+value+"'");
											linkage_field.setOrder(" ORDER BY VALUE ASC");
											linkage_field.getStore().load();
											linkage_field.setValue("");
											linkage_field.setRawValue("");
										}/*else if(fieldtype == "tree"){
											linkage_field.store.load({
												params : {
													parentId : value
												}
											});
											linkage_field.setValue("");
											linkage_field.setRawValue("");
										}*/

									}
								}
							}
						});
					break;
				}
				case Constants.FIELDSELECTCHOOSE:{
					//判断该字段是否有动态关联字段
					//var linkage = config.linkage || false;
					//动态关联字段
					//var linkagefield = config.linkagefield || "";
					//动态关联字段的查询字段
					//var linkagefilterfield = config.linkagefilterfield || "";
					//{"ftype":"select_choose","choose_objpath":"ROOT/XTGLPT/JCSJGL/YHXX/BLK_BASE_USERS","valuefield","USER_NO","displayvaluefield":"USER_NAME","required":true,"colspan":true}
					//弹出加载的业务模型路径
					var choose_objpath = config.choose_objpath;
					//确定或者双击行选择的回调数据值
					var valuefield = config.valuefield;
					//确定或者双击行选择的回调数据显示值
					var displayvaluefield = config.displayvaluefield;
					field = Ext.create("Ext.com.bkfm.combobox",{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						editable: false,
						objPath: metaField.obj_path,
						loadingText:'加载中……',
						style: "margin-top:10px;",
						queryMode: 'local',
						fieldCls: 'input_choose',
						readOnly: true,
						onTriggerClick: function(){
							var win = Ext.create('Ext.com.bkfm.window', {
									title: "数据选择",
									height : Utils.getHeight()*0.5,
									width : field.getWidth(),
									items:[Ext.create('Ext.com.bkfm.datagrid', {
										objPath : choose_objpath,
										border: true,
										showstandardBtn: false,
										checked: false,
										listeners:{
											itemdblclick: function(grid,record,item,index,e,eopts){
												field.fillValue({
													VALUE: record.get(valuefield),
													DISPLAYVALUE: record.get(displayvaluefield)
												});
												win.close();
											}
										}})],
									tbar:[{
										text: "确定",
										iconCls: 'ok',
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											var grid = win.items.items[0];
											var record = grid.getSelectedRecord();
											field.fillValue({
												VALUE: record.get(valuefield),
												DISPLAYVALUE: record.get(displayvaluefield)
											});
											win.close();
										}
									},{
										text: "关闭",
										iconCls: "close",
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											win.close();
										}
									},'->',{
										text: "高级查询",
										iconCls: "adsearch",
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											var grid = win.items.items[0];
											grid.customizeQuery();
										}
									}]
								}).show();
						}
					});				
					break;
				}
				case Constants.FIELDFILE:{
					//文件上传
					field = Ext.create("Ext.com.bkfm.combobox",{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						editable: false,
						objPath: metaField.obj_path,
						loadingText:'加载中……',
						style: "margin-top:10px;",
						queryMode: 'local',
						fieldCls: 'file_choose',
						readOnly: true,
						onTriggerClick: function(){
							AjaxUtils.CallFileUploadService(function(result,fileUploadWin){
								if(result.status == "OK"){
									var file = result.list[0];
									field.fillValue({
										VALUE: file.file_id,
										DISPLAYVALUE: file.file_name
									});
									fileUploadWin.close();
								}else{
									AjaxUtils.showError("文件上传失败",function(){
										fileUploadWin.close();
									});
								}
							});
							/*var win = Ext.create('Ext.com.bkfm.window', {
									title: "数据选择",
									height : Utils.getHeight()*0.5,
									width : field.getWidth(),
									items:[Ext.create('Ext.com.bkfm.datagrid', {
										objPath : choose_objpath,
										border: true,
										showstandardBtn: false,
										checked: false,
										listeners:{
											itemdblclick: function(grid,record,item,index,e,eopts){
												field.fillValue({
													VALUE: record.get(valuefield),
													DISPLAYVALUE: record.get(displayvaluefield)
												});
												win.close();
											}
										}})],
									tbar:[{
										text: "确定",
										iconCls: 'ok',
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											var grid = win.items.items[0];
											var record = grid.getSelectedRecord();
											field.fillValue({
												VALUE: record.get(valuefield),
												DISPLAYVALUE: record.get(displayvaluefield)
											});
											win.close();
										}
									},{
										text: "关闭",
										iconCls: "close",
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											win.close();
										}
									},'->',{
										text: "高级查询",
										iconCls: "adsearch",
										handler: function(self){
											var win = self.ownerCt.ownerCt;
											var grid = win.items.items[0];
											grid.customizeQuery();
										}
									}]
								}).show();*/
						}
					});
					break;
				}
				case Constants.FIELDDATE:{
					field = Ext.create('Ext.form.field.Date',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						//anchor:'90%',
						editable:false,
						format: config.format || 'Y-m-d',
						style: "margin-top:10px;"
					});
					break;
				}
				case Constants.FIELDNUMBER:{
					field = Ext.create('Ext.form.field.Number',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						maxLength: fieldlength,
						hideTrigger: true,
				        keyNavEnabled: false,
				        mouseWheelEnabled: false,
				        readOnly: field_editable,
				        enableKeyEvents: true,
				        style: "margin-top:10px;"
					});
					break;
				}
				case Constants.FIELDPASSWORD:{
					field = Ext.create('Ext.form.field.Text',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						maxLength: fieldlength,
						//anchor:'90%',
						inputType: 'password',
						readOnly: field_editable,
						enableKeyEvents: true,
						style: "margin-top:10px;"
					});
					break;
				}
				case Constants.FIELDCHECKBOX:{
					field = Ext.create('Ext.form.field.Checkbox',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						style: "margin-top:10px;",
						value: "1"
						//anchor:'90%'
					});
					break;
				}
				case Constants.FIELDTREE:{
					 field = Ext.create("Ext.com.bkfm.comboboxtree", {
						 msgTarget:'side',
					        //cascade : 'parent',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联
					        checkModel:'single',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选
					        fieldLabel: metaField.zh_cn,
					        id: metaField.en_us,
							name: metaField.en_us,
							labelAlign: form.labelAlign,
							labelWidth: form.labelWidth,
							labelSeparator: form.labelSeparator,
							editable:false,
							width: form.defaultWidth,
					        treeConfigId: config.treeConfigId,
					        rootId: config.rootTreeId,
					        rootText: config.rootTreeName || '',
					        treeNodeParameter : {

					        },
							listeners:{
								change: function(obj,value,oldvalue,opts){
									//判断是否存在动态二级菜单
									if(linkage && !Ext.isEmpty(linkagefield)){

										var linkage_field = form.findById(linkagefield);
										/*linkage_field.setFilter(" PARENTID='"+value+"'");
										linkage_field.getStore().load();
										linkage_field.setValue("");
										linkage_field.setRawValue("");*/
										linkage_field.store.load({
											params : {
												parentId : value
											}
										});
										linkage_field.setValue("");
										linkage_field.setRawValue("");
									}
								}
							}
					    });
					break;
				}
				case Constants.FIELDTEXTAREA:{
					field = Ext.create('Ext.form.field.TextArea',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						maxLength: fieldlength,
						style: "margin-top:10px;",
						enableKeyEvents: true,
						readOnly: field_editable
						//anchor:'90%'
					});
					break;
				}
				case Constants.FIELDHTML:{
					field = Ext.create('Ext.form.field.HtmlEditor',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						enableColors: false,
				        enableAlignments: false,
				        maxLength: fieldlength,
						style: "margin-top:10px;",
						enableKeyEvents: true,
						readOnly: field_editable,
					    getXType:function(){
					    	return "html"
					    }
						//anchor:'90%'
					});
					break;
				}
				case Constants.FIELDCHOOSE:{
					field = Ext.create('Ext.form.field.Text',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						maxLength: fieldlength,
						style: "margin-top:10px;",
						readOnly: field_editable,
						enableKeyEvents: true,
						style: "margin-top:10px;",
						fieldCls: 'input_choose'
						//anchor:'90%'
					});
					break;
				}
				default:{
					field = Ext.create('Ext.form.field.Text',{
						msgTarget:'side',
						fieldLabel: metaField.zh_cn,
						name: metaField.en_us,
						id: metaField.en_us,
						labelAlign: form.labelAlign,
						labelWidth: form.labelWidth,
						labelSeparator: form.labelSeparator,
						minWidth: form.defaultWidth,
						width: form.defaultWidth,
						allowBlank: allowBlank,
						maxLength: fieldlength,
						style: "margin-top:10px;",
						enableKeyEvents: true,
						readOnly: field_editable
						//anchor:'90%'
					});
					break;
				}
			}
		}
		if(this.columnCount ==1){
			field.setWidth(form.defaultWidth*3);
		}else{
			field.width = form.defaultWidth;
		}
		//debugger;
		field = this.parseReadOnlyField(field);
		field = this.parseHiddenField(field);
		//表单字段存放到字段数组中
		this.fieldItems.push(field);

		return field;
	},
	/**
	 * 判断用户是否设置了整个表单为只读类型，将整个表单所有字段设置为只读
	 */
	parseReadOnlyField: function(field){
		//判断当前表单是否制度
		if(this.textOnly){
			//整个表单为只读无需在判断单个字段是否为只读
			field.setReadOnly(true);
			if(field.getXType() != Constants.FIELDHTML){
				//非富文本编辑框
				field.setFieldStyle("background:none; border-right: 0px solid;border-top: 0px solid;border-left: 0px solid;border-bottom: #6699ff 2px solid;");
			}
			field.fieldCls = null;
			field.onTriggerClick = null;
			field.on("render",function(){
				var el = this.getEl().getById(this.getId()+"-triggerWrap");
				if(el){
					el.dom.style.border="0px";
				}
			});
		}else{
			var name = field.getId();
			//设置单个字段是否存在只读
			if(!Ext.isEmpty(this.textOnlyField)){
				if(Ext.Array.contains(this.textOnlyField,name)){
					field.setReadOnly(true);
					if(field.getXType() != Constants.FIELDHTML){
						//非富文本编辑框
						field.setFieldStyle("background:none; border-right: 0px solid;border-top: 0px solid;border-left: 0px solid;border-bottom: #6699ff 2px solid;");
					}
					field.fieldCls = null;
					field.onTriggerClick = null;
					field.on("render",function(){
						var el = this.getEl().getById(this.getId()+"-triggerWrap");
						if(el){
							el.dom.style.border="0px";
						}
					});

				}
			}
		}
		
		return field;
	},
	/**
	 * 单独设置只读字段
	 */
	setReadOnlyField: function(field){
		if(!field.readOnly){
			field.setReadOnly(true);
			if(field.getXType() != Constants.FIELDHTML){
				//非富文本编辑框
				field.setFieldStyle("background:none; border-right: 0px solid;border-top: 0px solid;border-left: 0px solid;border-bottom: #6699ff 2px solid;");
			}
			field.fieldCls = null;
			field.onTriggerClick = null;
			var el = field.getEl().getById(field.getId()+"-triggerWrap");
			if(el){
				el.dom.style.border="0px";
			}
		}
	},
	/**
	 * 设置字段可编辑
	 */
	setUnReadOnlyField: function(field){
		if(field.readOnly){
			//判断字段是否是只读
			field.setReadOnly(false);
			if(field.getXType()=="select" || field.getXType() == "datefield" || field.getXType() == "tree"){
				field.setFieldStyle("color: black;padding: 4px 6px 3px 6px;background: white repeat-x 0 0;border-width: 0px;border-style: solid;border-color: silver #d9d9d9 #d9d9d9;height: 24px; line-height: 15px;");
			}else{
				field.setFieldStyle("color: black;padding: 4px 6px 3px 6px;background: white repeat-x 0 0;border-width: 1px;border-style: solid;border-color: silver #d9d9d9 #d9d9d9;height: 24px; line-height: 15px;");
			}
			var el = field.getEl().getById(field.getId()+"-triggerWrap");
			if(el){
				el.dom.style.border="";
			}
		}
	},
	/**
	 * 转换表格字段，设置表格的每一列是否需要隐藏
	 * field: 表格列
	 */
	parseHiddenField: function(field){
		var name = field.getId();
		if(!Ext.isEmpty(this.hiddenField)){
			//debugger;
			if(Ext.Array.contains(this.hiddenField,name)){
				field.setVisible(false);
			}
		}
		return field;
	},
	//创建分组set
	createFieldSet: function(groupTitleName,field){
		var form = this;
		if(Ext.isEmpty(groupTitleName)){
			groupTitleName = Constants.FIELDGROUPOTHER;
		}
		var fieldSet = null;
		if(this.groupSet[groupTitleName]){
			fieldSet = this.groupSet[groupTitleName];
			//fieldSet.add(field);
			//设置面板中的元素
			fieldSet.itemSize = fieldSet.itemSize+1;
			return fieldSet;
		}else{
			//debugger;
			var fieldSetWidth = form.width ? form.width - 50 : form.defaultWidth*form.columnCount+25;
			fieldSet = Ext.create('Ext.form.FieldSet',{
				title: groupTitleName, // 指定 title 或者 checkboxToggle 配置项,都会创建 fieldset 组头(header).
				collapsible: true,
		        collapsed: false, // 初始化为收缩状态
		        //layout:'anchor',
		        width: fieldSetWidth,
		        itemSize: 1,//设置面板中的元素
				layout: {
					type: 'table',
					columns: form.columnCount,
					forceFit : true,
					bodyStyle: 'width:100%;'
				},
				bodyStyle:'width:600px'
		        //items:[field]
			});
			this.groupSet[groupTitleName] = fieldSet;
			//面板添加到窗体
			this.formItems.push(fieldSet);

			return fieldSet;
		}
	},
	//初始化表单分组
	initFormGroup: function(meta){
		this.groupSet = new Array();
		//定义每个字段在窗体中的索引位置
		var fieldIndex = 0;
		for(i in meta.list){
			var metaField = meta.list[i];
			var groupTitleName = metaField.group_title;
			var field = this.createFormField(metaField);
			if(field == null){
				continue;
			}
			var fieldSet = this.createFieldSet(groupTitleName,null);
			//检查是否需要合并行单元格
			this.colspanFieldCell(metaField,field,fieldSet.itemSize-1,fieldSet);
			fieldSet.add(field);

		}
	},
	/**
	 * 合并行单元格
	 * metaField 字段属性
	 * field 创建的字段
	 * fieldIndex 字段在窗体总的索引位置
	 * fieldPanel 字段容器面板
	 */
	colspanFieldCell: function(metaField,field,fieldIndex,fieldPanel){
		//定义表单元素序号,用户合并单元格
		var fieldIndex = fieldIndex+1;
		field.tabindex = fieldIndex;
		//判断是否需要合并单元格
		if(!Ext.isEmpty(metaField.user_config)){
			var config = Ext.JSON.decode(metaField.user_config);
			var colspan = config.colspan;//true需要填充一整行
			if(colspan){
				var colspanNum = this.columnCount-(fieldIndex % this.columnCount ==0 ? this.columnCount : fieldIndex % this.columnCount)+1;
				//alert(colspanNum);
				//debugger;
				field.colspan = colspanNum;

				field.setWidth(field.width * colspanNum);
				fieldIndex++;

				if(fieldPanel){
					fieldPanel.itemSize = fieldPanel.itemSize+(colspanNum-1);
				}
			}
		}
		return fieldIndex;
	}
	/**
	 * 设置表单状态
	 * @param status:new->新增，changed->修改
	 */
	,setFormState: function(status){
		this.formState = status;
	}
	/**
	 * 获取表单状态new：新增，changed:修改
	 */
	,getFormState: function(){
		return this.formState;
	}
	/**
	 * 设置表单记录的唯一序号
	 */
	,setFormRwid: function(rwid){
		this.rwid = rwid;
	}
	/**
	 * 获取表单记录的唯一序号
	 */
	,getFormRwid: function(){
		return this.rwid;
	}
	/**
	 * 获取表单填写的数据
	 */
	,getFormData: function(){
		var formData = {};
		if(this.fieldItems.length == 0){
			console.log("无效的表单面板，页面中没有字段");
			return null;
		}
		for(i in this.fieldItems){
			var field = this.fieldItems[i];
			var name = field.getName();
			var xtype = field.getXType();
			var value = "";
			switch(xtype){
				case 'select':{
					value = field.getValue();
					//debugger;
					break;
				}
				case 'select_choose':{
					value = field.getValue();
					//debugger;
					break;
				}
				case 'tree':{
					value = field.getSubmitValue();
					//debugger;
					break;
				}
				case 'datefield':{
					value = field.getRawValue();
					//debugger;
					break;
				}
				default:{
					value = field.getValue();
					break;
				}
			}
			formData[name] = value || "";
			//debugger;
		}
		return formData;
	},
	/**
	 * 根据元素id获取字段元素
	 * 返回查找到的字段元素
	 */
	findById: function(id){
		var id = Ext.util.Format.uppercase(id);
		var field = this.queryById(id);
		return field;
	},
	/**
	 * 设置字段值
	 */
	setFieldValue: function(field,v){
		if(!field){
			return;
		}
		var value = {

		};
		if(Utils.isJson(v)){
			value.VALUE = v.VALUE;
			value.DISPLAYVALUE = v.DISPLAYVALUE;
		}else{
			value.VALUE = v;
			value.DISPLAYVALUE = v;
		}
		v = value;
		//获取字段类型，分别设置
		var xtype = field.getXType();
		switch(xtype){
			case 'select':{
				field.fillValue(v);
				break;
			}
			case 'tree':{
				field.setValue(v.VALUE);
				if(!Ext.isEmpty(v.DISPLAYVALUE)){
					field.setRawValue(v.DISPLAYVALUE);
				}
				break;
			}
			case 'datefield':{
				//debugger;
				//var t = Ext.Date.parse(v.VALUE, "Y-m-d H:i:s");
				/*var t = new Date(v.VALUE);
				var d = Ext.Date.format(t,field.format || "Y-m-d") || v.VALUE;*/

				var value = v.VALUE;
				if(Ext.isEmpty(value)){
					field.setValue("");
					field.setRawValue("");
					break;
				}
				var date = new Date(Date.parse(value.replace(/-/g, "/")));
				var time = Ext.Date.format(date,field.format || "Y-m-d");
				field.setValue(time);
				field.setRawValue(time);
				break;
			}
			default:{
				field.setValue(v.VALUE);
				break;
			}
		}

	},
	/**
	 * 保存前执行
	 * callback: 执行函数最终能够结果返回true：false；true表示允许通过，false表示不通过
	 */
	beforeSave: Ext.emptyFn,
	/**
	 * 表单保存
	 */
	save: function(callback){
		if(this.beforeSave != Ext.emptyFn){
			var execute = Ext.callback(this.beforeSave,this,null);
			if(Ext.isEmpty(execute)){
				AjaxUtils.showError("执行函数“beforeSave”，没有返回值！");
				return ;
			}
			if(!execute){
				Utils.log("执行函数“beforeSave”，成功，返回false");
				return ;
			}
		}
		
		var form = this;
		if(this.isValid()){
			var savePath = this.objPath;
			if(!Ext.isEmpty(this.saveObjPath)){
				savePath = this.saveObjPath;
			}
			if(form.getFormData()==null){
				AjaxUtils.showError('表单没有权限');
				return;
			}
			var param = new Array();
			if(form.getFormState() == Constants.RECORD_NEW && Ext.isEmpty(form.getFormRwid())){
				//表单为新增，并且主键为空的情况下，设置表单新记录id
				form.setFormRwid(Utils.getRwid());
			}
			param.push({
				"obj_path": savePath,
				"record_state": form.getFormState(),
				"rwid": form.getFormRwid(),
				"record_data":Ext.JSON.encode(form.getFormData())
			});
			AjaxUtils.CallService({
				url: CONTEXT.contextPath+"/bkfm/metadata/v1/savemodelmetadata",
				dataType: "json",
				params: param,
				call: function(data){
					if(data.status == "OK"){
						form.setFormState(Constants.RECORD_CHANGED);
						if(Ext.isFunction(callback)){
							callback(data);
						}else{
							AjaxUtils.showInfo('操作成功');
						}

					}else{
						AjaxUtils.showError('操作失败');
					}
				}
			});
		}else{
			AjaxUtils.showError('当前表单验证不通过');
		}
	}
	,modifyRecord: function(r){
		if(r){
			this.setFormRwid(r.get("RWID"));
			this.setFormState(Constants.RECORD_CHANGED);

			for(i in this.fieldItems){
				var field = this.fieldItems[i];
				var name = field.getName();
				var xtype = field.getXType();
				var value = r.get(name) || "";
				var displayvalue = r.get(name+"_DISPLAYVALUE") || "";

				this.setFieldValue(field,{
					"VALUE": value,
					"DISPLAYVALUE": displayvalue
				});
			}
		}
	},
	/**
	 * 加载远程数据
	 * guid 查询的guid
	 * callback 回调函数，函数返回data
	 * filter 如果没有配置rwid主键，则使用filter过滤条件
	 */
	loadRemoteData: function(rwid,callback,filter){
		if(Ext.isEmpty(rwid) && Ext.isEmpty(filter)){
			AjaxUtils.showError('执行参数不合法,加载远程数据失败');
			return;
		}
		var form = this;
		AjaxUtils.CallService({
			url: CONTEXT.contextPath + "/bkfm/metadata/v1/querytablemodelmetadata",
			params: {
				"obj_path": form.objPath,
				"filter": Ext.isEmpty(filter)?" RWID='"+rwid+"'":filter
			},
			call: function(data){
				if(data.status == "OK"){
					form.setFormRwid(data.entity.RWID);
					form.setFormState(Constants.RECORD_CHANGED);
					//设置
					var f = new Array();
					for(name in data.entity){
						f.push(name);
					}
					//debugger;
					Ext.define('Result', {
					    extend: 'Ext.data.Model',
					    fields: f
					});

					var user = Ext.create('Result', data.entity);

					form.modifyRecord(user);

					if(callback){
						callback(data);
					}
				}else{
					if(callback){
						callback(data);
					}else{
						AjaxUtils.showError('加载远程数据失败');
					}
				}

			}
		});
	}
});
